import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';
import SmsService, { VerificationPurpose } from '@/utils/smsService';
import { generateToken } from '@/utils/auth';

export async function POST(request: NextRequest) {
  try {
    console.log('手机号登录API请求开始处理');
    const body = await request.json();
    const { phone, code } = body;
    
    console.log(`尝试通过手机号登录: ${phone}`);
    
    // 验证必填字段
    if (!phone || !code) {
      console.log('登录失败: 手机号或验证码为空');
      return NextResponse.json(
        { error: '手机号和验证码不能为空' },
        { status: 400 }
      );
    }
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      console.log('登录失败: 手机号格式不正确');
      return NextResponse.json(
        { error: '手机号格式不正确' },
        { status: 400 }
      );
    }
    
    // 验证验证码
    const isCodeValid = await SmsService.verifyCode(
      phone, 
      code, 
      'registration' as VerificationPurpose // 复用注册验证码类型
    );
    
    if (!isCodeValid) {
      console.log('登录失败: 验证码无效或已过期');
      return NextResponse.json(
        { error: '验证码无效或已过期' },
        { status: 400 }
      );
    }
    
    // 查找用户
    const user = await UserModel.findByPhone(phone);
    if (!user) {
      console.log('登录失败: 未找到该手机号关联的用户');
      return NextResponse.json(
        { error: '未找到该手机号关联的用户，请先注册' },
        { status: 404 }
      );
    }
    
    // 生成JWT令牌
    const token = generateToken({
      id: user.id,
      username: user.username
    });
    
    // 返回用户信息（不包含密码）
    const { password, ...userWithoutPassword } = user;
    
    console.log('手机号登录成功');
    return NextResponse.json({
      success: true,
      message: '登录成功',
      token,
      user: userWithoutPassword
    });
  } catch (error) {
    console.error('手机号登录处理过程中发生错误:', error);
    return NextResponse.json(
      { 
        success: false,
        error: '服务器错误，请稍后再试', 
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}
